package com.loongxun.playwithyou;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loongxun.playwithyou.bean.Member;
import com.loongxun.playwithyou.bean.SendRequest;
import com.loongxun.playwithyou.network.MyHttpClientRespenseHandler;
import com.loongxun.playwithyou.network.nHttpClient;
import com.loongxun.playwithyou.ui.activity.BespeakActivity;
import com.loongxun.playwithyou.ui.activity.LoginActivity;
import com.loongxun.playwithyou.ui.activity.PlatformActivity;
import com.loongxun.playwithyou.ui.adapter.MemberAdapter;
import com.loongxun.playwithyou.util.ToastView;
import com.loongxun.playwithyou.view.pullableview.MyListener;
import com.loongxun.playwithyou.view.pullableview.PullToRefreshLayout;
import com.nineoldandroids.view.ViewHelper;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by Administrator on 2017/7/18.
 */
public class MainActivity extends FragmentActivity implements View.OnClickListener/*,PullToRefreshSwipeMenuListView.IXListViewListener*/{

    private DrawerLayout mDrawerLayout;
    //性别
    private int sex;
    private List<Member> members = new ArrayList<>();
    private Context context;
    private SendRequest send;

    //用户编辑器
    private SharedPreferences share;
    private SharedPreferences.Editor editor;
    private String  user_id;

//    private PullToRefreshSwipeMenuListView lv_member_list;
//    private Handler mHandler;
    private ListView listView;
    private PullToRefreshLayout ptrl;
    private boolean isFirstIn = true;

    private MemberAdapter mAdapter;
    private TextView tv_left_sex_0,tv_right_sex_1,tv_top_title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = MainActivity.this;

        share = context.getSharedPreferences("userInfo", 0);
        editor = share.edit();

        tv_top_title = (TextView) findViewById(R.id.tv_top_title);
        tv_top_title.setText("手游私教");

//        lv_member_list = (PullToRefreshSwipeMenuListView) findViewById(R.id.lv_member_list);
//        lv_member_list.setPullRefreshEnable(true);
//        lv_member_list.setPullLoadEnable(false);
//        lv_member_list.setXListViewListener(this);
//        mHandler = new Handler();

        ptrl = ((PullToRefreshLayout) findViewById(R.id.refresh_view));
        ptrl.setOnRefreshListener(new MyListener());
        listView = (ListView) findViewById(R.id.content_view);
        ptrl.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        initData();
                        // 千万别忘了告诉控件刷新完毕了哦！
                        pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 3000);
            }

            @Override
            public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // 千万别忘了告诉控件刷新完毕了哦！
                        pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 3000);

            }
        });
        ptrl.autoRefresh();

        initData();
        initView();
        initEvents();
    }

    public void OpenRightMenu(View view) {
        mDrawerLayout.openDrawer(Gravity.LEFT);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
    }

    private void initEvents() {
        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerStateChanged(int newState) {
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                View mContent = mDrawerLayout.getChildAt(0);
                float scale = 1 - slideOffset;
//                float rightScale = 0.8f + scale * 0.2f;
                float leftScale = 1 - 0.3f * scale;
                ViewHelper.setScaleX(drawerView, leftScale);
                ViewHelper.setScaleY(drawerView, leftScale);
                ViewHelper.setAlpha(drawerView, 0.6f + 0.4f * (1 - scale));
                ViewHelper.setTranslationX(mContent, drawerView.getMeasuredWidth() * (1 - scale));
                ViewHelper.setPivotX(mContent, 0);
                ViewHelper.setPivotY(mContent, mContent.getMeasuredHeight() / 2);
                mContent.invalidate();
//                ViewHelper.setScaleX(mContent, rightScale);
//                ViewHelper.setScaleY(mContent, rightScale);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
            }
        });
    }

    private void initView() {
        findViewById(R.id.ll_btm_left).setOnClickListener(this);
        findViewById(R.id.ll_btm_right).setOnClickListener(this);

        findViewById(R.id.top_left_user).setOnClickListener(this);
        findViewById(R.id.top_right_search).setOnClickListener(this);
        findViewById(R.id.tv_screen).setOnClickListener(this);
        tv_left_sex_0 = (TextView) findViewById(R.id.tv_left_sex_0);
        tv_left_sex_0.setOnClickListener(this);
        tv_right_sex_1 = (TextView) findViewById(R.id.tv_right_sex_1);
        tv_right_sex_1.setOnClickListener(this);
        sex = 0;
        tv_left_sex_0.setSelected(true);
        tv_right_sex_1.setSelected(false);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawerLayout);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
    }

    private void initData() {
        try {
            send = new SendRequest();
            send.memberSex = sex+"";
            //判断此会员是否为陪玩人员
            nHttpClient.getAll(ApiInterface.INDEX_LIST, send.toIndexListJson().toString(), indexHandler);
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        // 第一次进入自动刷新
        if (isFirstIn) {
            ptrl.autoRefresh();
            isFirstIn = false;
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()){
            case R.id.top_left_user:
                OpenRightMenu(view);
                break;
            case R.id.top_right_search:
                Toast.makeText(this, "搜索", Toast.LENGTH_SHORT).show();
                break;
            case R.id.tv_screen:
                Toast.makeText(this,"筛选",Toast.LENGTH_SHORT).show();
                break;
            //平台介绍
            case R.id.ll_btm_left:
                intent = new Intent(context, PlatformActivity.class);
                startActivity(intent);
                break;
            //预约
            case R.id.ll_btm_right:
                user_id = share.getString("user_id", "");
                if (isLogin(user_id)) {
                    intent = new Intent(context, BespeakActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.tv_left_sex_0:
                sex = 0;
                initData();
                tv_left_sex_0.setSelected(true);
                tv_right_sex_1.setSelected(false);
                tv_right_sex_1.setBackgroundResource(R.color.transparent);
                tv_left_sex_0.setBackgroundResource(R.drawable.corners_bg_5_white_left);
                break;
            case R.id.tv_right_sex_1:
                sex = 1;
                initData();
                tv_left_sex_0.setSelected(false);
                tv_right_sex_1.setSelected(true);
                tv_left_sex_0.setBackgroundResource(R.color.transparent);
                tv_right_sex_1.setBackgroundResource(R.drawable.corners_bg_5_white_right);
                break;
            default:
                break;
        }
    }

    private MyHttpClientRespenseHandler indexHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            JSONArray itemArray;
            if (succeed == 1) {
                try {
                    itemArray = json.getJSONArray("data");
                    members.clear();
                    for(int i = 0;i < itemArray.length();i++) {
                        JSONObject subItemObject = itemArray.getJSONObject(i);
                        Member member = new Member();
                        member.setMember_id(subItemObject.optInt("member_id",0));
                        member.setClick_num(subItemObject.optInt("click_num", 0));
                        member.setMember_address(subItemObject.optString("member_address"));
                        member.setMember_img(subItemObject.optString("member_img"));
                        member.setMember_sex(subItemObject.optInt("member_sex", 0));
                        member.setMember_name(subItemObject.optString("member_name"));
                        members.add(member);
                    }
                    mAdapter = new MemberAdapter(context,members);
//                    lv_member_list.setAdapter(mAdapter);
                    listView.setAdapter(mAdapter);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                Toast.makeText(context, error_desc, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void faile(String json) {
            Toast.makeText(context, json, Toast.LENGTH_SHORT).show();
        }
    };

    private boolean isExit = false;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit=false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if (isExit == false) {
                isExit = true;
                Toast.makeText(this,"再按一次退出APP",Toast.LENGTH_SHORT).show();
                handler.sendEmptyMessageDelayed(0, 3000);
            }else {
                finish();
                return false;
            }
        }
        return true;
    }

    private boolean isLogin(String user_id) {
        if (user_id.equals("")){
            Intent intent = new Intent(context, LoginActivity.class);
            startActivityForResult(intent,0);
            return false;
        }
        return true;
    }

//    @Override
//    public void onRefresh() {
////        mHandler.postDelayed(new Runnable() {
////            @Override
////            public void run() {
////                SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
////                RefreshTime.setRefreshTime(getApplicationContext(), df.format(new Date()));
////                initData();
////                lv_member_list.setRefreshTime(RefreshTime.getRefreshTime(getApplicationContext()));
////                lv_member_list.stopRefresh();
////                lv_member_list.stopLoadMore();
////            }
////        }, 100);
//    }
//
//    @Override
//    public void onLoadMore() {
//
//    }
}
